package task

import db.WaresCargo
import event.AckEvent
import event.DeliveryTaskEvent
import ext.log
import manager.DeliveryManager
import org.greenrobot.eventbus.EventBus
import java.io.IOException
import java.util.concurrent.LinkedBlockingDeque
import java.util.concurrent.TimeUnit


class DeliveryTask(private val waresCargo: WaresCargo, private val isHot: Boolean) : Runnable {

    private val queue = LinkedBlockingDeque<AckEvent>()

    private fun exec() {
        val cargo = waresCargo.findNormalCargoAndDelete() // 查找没有过期的货道并删除之， 如果没有找到则抛异常
        log("开始出货:$cargo")
        var heat = waresCargo.wares.heatTempValue.toInt()
        if (heat < 0) {
            heat = 0
        }
        if (isHot) {
            DeliveryManager.delivery(
                cargo.col,
                cargo.row,
                waresCargo.wares.waveHeatTime.toInt(), // 微波时间
                waresCargo.wares.infraredHeatTime.toInt(), // 红外时间
                heat, // 红外温度
                waresCargo.wares.heatDissipationTime, // 散热时间
                ::onAckEvent
            )
        } else {
            DeliveryManager.delivery(
                cargo.col,
                cargo.row,
                0, // 微波时间
                0, // 红外时间
                0,// 温度
                0,
                ::onAckEvent
            )
        }

        val env = queue.poll(5, TimeUnit.SECONDS)

        if (env == null) {
            throw IOException("串口发送异常")
        }

        if (env.status == AckEvent.OK) {
            log("串口发送成功返回")
            EventBus.getDefault().post( DeliveryTaskEvent(cargo) )
        } else {
            throw IOException("串口发送错误")
        }
    }

    private fun onAckEvent(env: AckEvent?) {
        if (env != null) {
            queue.put(env)
        }
    }

    override fun run() {
        queue.clear()
        try {
            exec()
        } catch (e: Exception) {
            e.printStackTrace()
            EventBus.getDefault().post( DeliveryTaskEvent(null) )
        }
    }
}

